import { Table, Popconfirm, message } from "antd";
import { EditOutlined, DeleteOutlined, CloseOutlined } from "@ant-design/icons";
import { useEffect } from "react";
import { Button, Card as SemiCard, Row, Col, List, ButtonGroup } from "@douyinfe/semi-ui";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { IconPlusCircle } from "@douyinfe/semi-icons";

import { AllRoles, GetMembers, GetApplications, RemoveMember } from "../_graphql/roles";

import RoleMemberAddModal from "../_modals/member/add";
import { Space } from "antd";

const { Column } = Table;

const ApplicationRoles = () => {
    const { windowInnerHeight, graphqlFetch } = useModel("global");
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent, setModalStyle } = useModel("global.modal");

    const state = useReactive({
        loading: false,
        loadingMembers: false,
        loadingApplications: false,
        roles: [],
        members: [],
        applications: [],
        selectedRole: {},
        totalCount: 0,
        pageSize: 20,
        page: 1,
    });

    const loadRoles = async () => {
        state.loading = true;
        let res = await graphqlFetch({
            query: AllRoles,
            variables: {},
        });
        state.roles = res?.a?.nodes || [];
        let selectedRole = state.roles.find((item) => item.arUuid === state.selectedRole?.arUuid);
        !selectedRole && state.roles.length > 0 && (selectedRole = state.roles[0]);
        state.selectedRole = selectedRole;
        state.loading = false;
    };

    const loadRoleMembers = async () => {
        state.loadingMembers = true;
        let res = await graphqlFetch({
            query: GetMembers,
            variables: { arUuid: state.selectedRole?.arUuid },
        });
        state.members = res?.a?.nodes || [];
        state.loadingMembers = false;
    };

    const loadRoleApplications = async () => {
        state.loadingApplications = true;
        let res = await graphqlFetch({
            query: GetApplications,
            variables: { arName: state.selectedRole?.arName },
        });
        state.applications = res?.a?.nodes || [];
        state.loadingApplications = false;
    };

    useEffect(() => {
        loadRoles();
    }, []);

    useEffect(() => {
        if (state.selectedRole?.arName) {
            loadRoleApplications();
            loadRoleMembers();
        }
    }, [state.selectedRole]);

    const openRoleMemberAddModal = () => {
        setModalTitle("添加角色人员");
        setModalVisible(true);
        setModalWidth(500);
        setModalStyle({ top: 100 });
        setModalComponent(<RoleMemberAddModal role={state.selectedRole} members={state.members} reloadData={loadRoleMembers} />);
    };

    const handleRemoveMember = async (member) => {
        let res = await graphqlFetch({
            query: RemoveMember,
            variables: { arUuid: state.selectedRole.arUuid, omUuid: member.omUuid },
        });
        if (res) {
            message.success("成功移除角色成员");
            await loadRoleMembers();
        }
    };

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 54;

    return (
        <div style={{ padding: 10 }}>
            <Row gutter={10}>
                <Col span={4}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 15 }}>应用角色列表</span>}
                        headerStyle={{ padding: "10px 14px" }}
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 1, height: cardBodyHeight, overflow: "auto" }}
                    >
                        <List
                            loading={state.loading}
                            dataSource={state.roles}
                            renderItem={(item) => (
                                <List.Item
                                    className={`list-item ${state.selectedRole?.arUuid === item.arUuid ? "list-item-selected" : ""}`}
                                    onClick={() => (state.selectedRole = item)}
                                >
                                    {item.arName}
                                </List.Item>
                            )}
                        />
                    </SemiCard>
                </Col>
                <Col span={20}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 15 }}>角色人员列表</span>}
                        headerStyle={{ padding: "10px 14px" }}
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 0, height: 200 }}
                        style={{ marginBottom: 10 }}
                        headerExtraContent={
                            <ButtonGroup>
                                {state.selectedRole?.arUuid && (
                                    <Button title="添加角色人员" icon={<IconPlusCircle />} onClick={() => openRoleMemberAddModal()}>
                                        添加人员
                                    </Button>
                                )}
                            </ButtonGroup>
                        }
                    >
                        <List
                            loading={state.loadingMembers}
                            dataSource={state.members}
                            grid={{ gutter: 16, xs: 3, sm: 4, md: 6, lg: 6, xl: 6, xxl: 6 }}
                            style={{ padding: 16 }}
                            renderItem={(item) => (
                                <List.Item>
                                    <Space>
                                        <div>
                                            {item.member.omName} ({item.member.omIfim ? "内部" : "外部"})
                                        </div>
                                        <div>
                                            <Popconfirm title="确认要移除该成员吗？" onConfirm={() => handleRemoveMember(item.member)}>
                                                <CloseOutlined title="移除" style={{ color: "red", fontSize: 12 }} />
                                            </Popconfirm>
                                        </div>
                                    </Space>
                                </List.Item>
                            )}
                        />
                    </SemiCard>

                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 15 }}>角色应用列表</span>}
                        headerStyle={{ padding: "10px 14px" }}
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 0, height: cardBodyHeight / 2 + 168 }}
                    >
                        <Table
                            loading={state.loadingApplications}
                            bordered
                            size="small"
                            pagination={false}
                            dataSource={state.applications}
                            rowKey={(record) => record.aiUuid}
                            scroll={{ y: cardBodyHeight / 2 + 168 - 40 }}
                        >
                            <Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
                            <Column title="应用名称" dataIndex={"aiName"} align="left" />
                            <Column title="应用分类" dataIndex={"aiClas"} align="center" />
                            <Column title="收费状态" dataIndex={"aiFree"} align="center" render={(_, r, i) => (_ ? "免费" : "收费")} />
                            <Column title="授权开始日期" dataIndex={"aiStda"} align="center" />
                            <Column title="授权结束日期" dataIndex={"aiEnda"} align="center" />
                            <Column title="可用状态" dataIndex={"aiStat"} align="center" render={(_, r, i) => (_ ? "正常" : "禁用")} />
                        </Table>
                    </SemiCard>
                </Col>
            </Row>
        </div>
    );
};

export default ApplicationRoles;
